package site.assad.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import site.assad.domain.User;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Author: Al-assad 余林颖
 * E-mail: yulinying_1994@outlook.com
 * Date: 2017/12/17 12:52
 * Description:
 */
@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //查找user
    public User findUserByName(final String userName){
        final String sql = "SELECT user_id,user_name,user_password,user_credits,last_visit,last_ip " +
                "FROM user " +
                "WHERE user_name = ? ";
        User user = new User();
        jdbcTemplate.query(sql, new Object[]{userName}, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                user.setId(rs.getInt("user_id"));
                user.setName(rs.getString("user_name"));
                user.setPassword(rs.getString("user_password"));
                user.setCredits(rs.getInt("user_credits"));
                user.setLastVisit(rs.getDate("last_visit"));
                user.setLastIp(rs.getString("last_ip"));
            }
        });
        return user;
    }

    //user密码验证
    public int getUserPassowrdMatchCount(final String userName,final String password){
        final String sql = "SELECT COUNT(user_id) FROM user WHERE user_name=? and user_password=? ";
        return jdbcTemplate.queryForObject(sql,new Object[]{userName,password},Integer.class);
    }

    //更新user登陆信息
    public void updateLoginInfo(User user){
        final String sql = "UPDATE user " +
                "SET user_credits=?,last_visit=?,last_ip=?" +
                "WHERE user_id = ? ";
        jdbcTemplate.update(sql,new Object[]{user.getCredits(),user.getLastVisit(),user.getLastIp(),user.getId()});
    }

    //添加用户
    public void addUser(User user){
        final String sql = "INSERT INTO user(user_name,user_password,user_credits,last_visit,last_ip) " +
                "VALUES(?,?,?,?,?)";
        jdbcTemplate.update(sql,new Object[]{
                user.getName(),
                user.getPassword(),
                user.getCredits(),
                user.getLastVisit(),
                user.getLastIp()  });
    }

    //更新用户全部信息
    public void updateUser(User user){
        final String sql = "UPDATE user " +
                "SET user_name=?,user_password=?,user_credits=?,last_visit=?,last_ip=?" +
                "WHERE user_id=?";
        jdbcTemplate.update(sql,new Object[]{
                user.getName(),
                user.getPassword(),
                user.getCredits(),
                user.getLastVisit(),
                user.getLastIp(),
                user.getId()
        });
    }




}
